<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.username"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入用户名"
      />
      <el-input
        v-model="listQuery.phone"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入手机号"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        >查找</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
        >注册</el-button
      >
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" width="100px" label="序号" type="index" sortable />
      <!-- <el-table-column align="center" width="100px" label="ID" prop="id" /> -->

      <el-table-column align="center" label="账号" prop="username" />
      <el-table-column align="center" label="姓名" prop="name" />

      <el-table-column align="center" label="手机号码" prop="phone" />
      <!-- <el-table-column align="center" label="机器编号" prop="equipmentNo" />
      <el-table-column align="center" label="产品标签" prop="productFlag" /> -->
      <!-- <el-table-column align="center" label="协议版本号" prop="agreementVersion" /> -->

      <el-table-column
        align="center"
        label="操作"
        width="400"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleDetail(scope.row,'look')"
            >查看</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleDetail(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="updatePassword(scope.row)"
            >修改密码</el-button
          >
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="changePagination"
    />
    <!-- 用户编辑对话框 -->
    <el-dialog :visible.sync="dialogFormVisible" :title="textMap[dialogStatus]"
      :close-on-click-modal="false">
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        :disabled="dialogStatus=='look'"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="账号" prop="username">
          <el-input :disabled="dialogStatus!=='create'" placeholder="请输入账号" :maxlength="33" v-model.trim="dataForm.username" />
        </el-form-item>
        <el-form-item v-if="dialogStatus=='create'||dialogStatus=='updatePassword'" :maxlength="20" label="密码" prop="password">
          <el-input
            v-model.trim="dataForm.password"
            type="password"
            placeholder="请输入密码"
            auto-complete="off"
          />
        </el-form-item>
        <el-form-item v-if="dialogStatus=='create'||dialogStatus=='updatePassword'" label="确认密码" prop="newPassword2">
          <el-input :maxlength="20" v-model="dataForm.newPassword2" placeholder="请输入确认密码" type="password" auto-complete="off"/>
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='updatePassword'" label="姓名" prop="name">
          <el-input :maxlength="10" placeholder="请输入姓名" v-model.trim="dataForm.name" />
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='updatePassword'" label="手机号" prop="phone">
          <el-input :maxlength="11" placeholder="请输入手机号" v-model.number="dataForm.phone" />
        </el-form-item>
        <!-- <el-form-item v-if="dialogStatus=='create'" label="机器编号" prop="equipmentNo">
          <el-input :maxlength="33" placeholder="请输入机器编号" v-model.trim="dataForm.equipmentNo" />
        </el-form-item>
        <el-form-item v-if="dialogStatus=='create'" label="产品标签" prop="productFlag">
          <el-input :maxlength="33" placeholder="请输入产品标签" v-model.trim="dataForm.productFlag" />
        </el-form-item>
        <el-form-item label="协议版本号" prop="agreementVersion">
          <el-input :maxlength="33" placeholder="请输入协议版本号" v-model.trim="dataForm.agreementVersion" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="dialogStatus!=='look'">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="onSumit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMember, createMember, updateMember,deleteMember,updatePws } from '@/api/member'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import md5 from 'md5' 
export default {
  name: 'member',
  components: { Pagination },
  data () {
    var validatePass = (rule, value, callback) => {
      var reg=/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z~!@#$%^&*()_+`\-={}:";'<>?,./]{8,16}$/  //8-16位且同时包含数字和字母
      console.log("reg.test(value)",value,!reg.test(value))
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (!reg.test(value)) {
        callback(new Error('密码由8-16位且同时包含数字和字母组成!'))
      } else {
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.dataForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var validatePhone = (rule, value, callback) => {
      var reg=/^1[3|4|5|7|8|9][0-9]\d{8}$/
      if (value === '') {
        callback(new Error('请输入手机号'))
      }else if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号码!'))
      } else {
        callback()
      }
    }
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 10,
        username: undefined,
        phone: undefined,
      },
      dialogFormVisible: false,
      dataForm:{
        id: undefined,
        username: undefined,
        password: undefined,
        newPassword2: undefined,
        name: undefined,
        phone: undefined,
        // equipmentNo: undefined,
        // productFlag: undefined,
        // agreementVersion: undefined,
      },
      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        newPassword2: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        // equipmentNo: [
        //   { required: true, message: '机器编号不能为空', trigger: 'blur' },
        // ],
        // productFlag: [
        //   { required: true, message: '产品标签不能为空', trigger: 'blur' },
        // ],
        // agreementVersion: [
        //   { required: true, message: '协议版本号不能为空', trigger: 'blur' },
        // ],
      },
      dialogStatus: '',
      // selectRoles:[],
      textMap: {
        look: '查看',
        create: '创建',
        update: '编辑',
        updatePassword: '修改密码',
      },
    }
  },
  created () {
    this.getList()
  },
  methods: {
    getList () {
      this.listLoading = true
      listMember(this.listQuery).then(response => {
        console.log("response.data.code",response.data.code)
        if(response.data.code==200){
          this.list = response.data.data.records
          this.total = response.data.data.total
          this.listLoading = false
        }
      }).finally(() => this.listLoading = false)
    },
    changePagination ({ page, limit }) {
      // console.log('changePagination', page, limit)
      if (page) this.listQuery.current = page
      if (limit) this.listQuery.size = limit
      this.getList()
    },
    handleFilter () {
      this.listQuery.page = 1
      this.getList()
    },
    createData () {
      this.$refs['dataForm'].validate(valid => {
        if (valid && !this.loading) {
          this.loading = true
          let data = JSON.parse(JSON.stringify(this.dataForm))
          data.password = md5(data.password)
          createMember(data)
            .then(response => {
              if(response.data.code==200){
                this.list.unshift(response.data.data)
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '会员注册成功',
                  duration: 3000
                })
                this.getList()
              }
            })
            .finally(() => this.loading = false)
        }
      })
    },
    resetForm () {
      this.dataForm =  {
        id: undefined,
        username: undefined,
        password: undefined,
        newPassword2: undefined,
        name: undefined,
        phone: undefined,
        // equipmentNo: undefined,
        // productFlag: undefined,
        // agreementVersion: undefined,
      }
    },
    handleCreate () {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updatePassword (row) {
      this.resetForm()
      this.dataForm = Object.assign({},row)
      this.dataForm.password=""
      this.dialogStatus = 'updatePassword'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDetail (row,type) {
      this.dataForm = row
      this.dialogStatus = type||"update"
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    onSumit () {
      if(this.dialogStatus=="create"){
        this.createData()
      }else if(this.dialogStatus=="update"){
        this.handleUserUpdate()
      }else{
        this.handleUpdatePassword()
      }
    },
    handleUserUpdate () {
      this.$refs['dataForm'].validate(valid => {
        if (valid && !this.loading) {
          this.loading = true
          updateMember(this.dataForm)
            .then(response => {
              if(response.data.code==200){
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新用户成功'
                })
                this.getList()
              }
            })
            .finally(() => this.loading = false)
        }
      })
    },
    handleUpdatePassword () {
      this.$refs['dataForm'].validate(valid => {
        if (valid && !this.loading) {
          this.loading = true
          let data={
            userId:this.dataForm.id,
            password:md5(this.dataForm.password),
          }
          updatePws(data)
            .then(response => {
              if(response.data.code==200){
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '修改密码成功'
                })
              }
            })
            .finally(() => this.loading = false)
        }
      })
    },
    handleDelete (row) {
      this.$confirm('确定删除这个会员吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteMember({id:row.id}).then(response => {
            if(response.data.code==200){
              this.$notify.success({
                title: '成功',
                message: '删除会员成功',
                duration: 3000
              })
              if (
                this.total > this.listQuery.size &&
                this.total % this.listQuery.size === 1
              ) {
                this.listQuery.current -= 1
              }
              this.getList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>
